
/**
 * 结汇
 */
 layui.define(['layer', 'form','laytpl'], function (exports) {
    var $ = layui.jquery, layer = layui.layer, form = layui.form , com = layui.com,
        request = layui.request,laytpl = layui.laytpl
        fn = {
            //确认汇率倒计时秒数
            countdownSeconds:15,
            rateData: null,
            layer_index:0,
            params: {
                page: 1
                , limit: 5
            },
            list:[],
            clearQuery(){
                fn.params.page = 1;
                fn.params.limit = 5;
                fn.query();
            },
            init(){
                request.get('/rate/txn/queryAcctCurrency').then(res=>{
                    if(res.data != null && res.data.length > 0) {
                        let sellCurs = res.data.filter(item => item.value != 'CNY');
                        com.fullSelect({
                            elem:$('#sellCur'),
                            data:sellCurs,
                            label:'label',
                            value:'value',
                            defValue:'',
                            firstLabel:'请选择'
                        });
                        form.render('select','form-txn-info');
                    }
                });
            },
            handleMessageTime(time) {
                let timer = setInterval(() => {
                    if (time === 0) {
                        clearInterval(timer);
                        //移除确认汇率按钮
                        $("#confirmRateBtn").attr({'disabled':true}).addClass('layui-btn-disabled').html('确认汇率');
                        //放开询价按钮
                        $(".queryPrice-btn").attr("disabled",null);
                        $(".queryPrice-btn").removeClass('layui-btn-disabled');
                        //解除询价页面录入要素禁用
                        let $form = $('#form-txn-info');
                        $form.removeClass('form-disabled');
                        $form.find('input').attr({'disabled':null});
                        $form.find('select').attr({'disabled':null});
                        $form.find('input').removeClass("layui-disabled");
                        $form.find('select').removeClass("layui-disabled");

                        $(".settlement-warn").hide();
                        $(".settlement-confirm").hide();
                        $(".settlement-rate").hide();
                        //汇率概况面板重新赋值
                        $("#settlement-sell").text('-');
                        $("#settlement-buy").text('-');
                        $("#settlement-exchangeRate").text('-');

                        form.render(null,'form-txn-info');

                    } else {
                        fn.countdownSeconds = time;
                        $("#confirmRateBtn").attr({'disabled':null}).removeClass('layui-btn-disabled').html('确认汇率(' + fn.countdownSeconds+'秒后失效)');
                        time--;
                    }
                }, 1000);
            },
            showQueryRate(){
                //确认按钮禁用并不显示
                $("#confirmRateBtn").attr({'disabled':true}).addClass('layui-btn-disabled').html('确认汇率');
                $(".settlement-confirm").hide();
                $(".settlement-warn").hide();
                //放开询价按钮
                $(".queryPrice-btn").attr("disabled",null);
                $(".queryPrice-btn").removeClass('layui-btn-disabled');
                //放开询价表单
                //解除询价页面录入要素禁用
                let $form = $('#form-txn-info');
                $form.removeClass('form-disabled');
                $form.find('input').attr({'disabled':null});
                $form.find('select').attr({'disabled':null});
                form.render('select','form-txn-info');
                form.render('radio','form-txn-info');
                //清空询价数据
                fn.rateData = null;
            },
            async query(){
                com.showLoading();
                fn.list = [];
                let params = {};
                params.inStatus = '02';
                request.postForm('/rate/txn/txnList',params).then(res => {
                    fn.list = res.data;
                    // 模板渲染
                    laytpl($('#tpl-txn-list').html()).render(res.data, function (html) {
                        $('#tab-txn-list').find('tbody').remove();
                        $('#tab-txn-list').append(html);
                        // 重新渲染表单内表单数据
                        com.chooseCheckbox($('#checkbox-txn-list-check-all'),false);
                        form.render(null, 'form-txn-list');
                    });
                    $.each(res.data || [],function (i,o) {
                        if(o.orderStatus == '01') {
                            laytpl($('#tpl-order').html()).render(o, function (html){
                                $('div[status-id="' + o.id +'"]').html(html);
                            });
                        }
                    });
                    // 开启分页
                    com.paginationNoLimit('txn-list-pagination', res.count, fn.params, function () {
                        fn.query();
                    });
                     // 初始化复制功能
                     com.createCopyContent();
                    if(res.count>0){
                        $('#txn-list-pagination').show();
                        $('.blank-list').hide();
                    }else{
                        $('#txn-list-pagination').hide();
                        $('.blank-list').show();
                    }
                });
            },
            async declare(txnNo){
                await $.get('/views/sub/rateSettlementDeclare.html',{},function (html) {
                    fn.layer_index = layer.open({
                        title: '新增收支交易类别'
                        , id: 'win-rate-settlement-declare'
                        , type: 1
                        , resize: false
                        , shadeClose: true
                        , area: ['550px', 'auto']
                        , content: html
                    });
                });
                $('#rate-settlement-declare-txnNo').val(txnNo);
                form.render('select');
                form.on('submit(save-rate-settlement-declare)',function (data) {
                    request.postForm('/rate/txn/declare',data.field).then((res)=>{
                        layer.close(fn.layer_index);
                        layer.msg('新增成功');
                        //重新加载列表
                        fn.clearQuery();
                    });
                });
            },
            //交易信息
            async show(id,type){
                //此处区分结汇/购汇
                await $.get('/views/sub/showSettleRateTxn.html',{'id':id},function (html) {
                    fn.layer_index = layer.open({
                        title: '交易信息'
                        , id: 'win-rate-txn'
                        , type: 1
                        , resize: false
                        , shadeClose: true
                        , area: ['550px', 'auto']
                        , content: html
                    });
                });
                await request.get('/rate/txn/detailById?id=' + id).then(res =>{
                    form.val('form-txn-detail',res.data);
                }).catch(()=>{
                    layer.close(fn.layer_index);
                });
            }
        };
    fn.init();
    fn.clearQuery();
    form.render(null, 'form-txn-list');
    form.render('select','form-txn-info');
    form.render('radio','form-txn-info');
    //询价
    form.on('submit(queryPrice-submit)', function (data) {
        let params = data.field;
        request.postForm('/rate/txn/queryPrice',params).then(res => {
            fn.rateData = res.data;
            //显示数据
            $(".settlement-warn").show();
            $(".settlement-confirm").show();
            $(".settlement-rate").show();

            //卖出金额币种
            $("#settlement-sell").text(res.data.sellAmt + "  " + res.data.sellCur);
            //买入金额币种
            $("#settlement-buy").text(res.data.buyAmt + "  " + res.data.buyCur);
            //汇率
            $("#settlement-exchangeRate").text(res.data.rate);
            $("#settlement-realExchangeRate").text('实际交易汇率：' + res.data.queryRate);

            //禁用交易详情按钮，倒计时结束恢复
            $(".queryPrice-btn").attr("disabled",true);
            $(".queryPrice-btn").addClass('layui-btn-disabled');

            //禁用表单
            let $form = $('#form-txn-info');
            $form.addClass('form-disabled');
            $form.find('input').attr({'disabled':true});
            $form.find('select').attr({'disabled':true});
            form.render('select','form-txn-info');
            form.render('radio','form-txn-info');

            com.setLocalStorage('$rateQueryPrice', moment().valueOf() / 1000);
            fn.handleMessageTime(15);

        });
    });
    //确认汇率
    $("#confirmRateBtn").on("click",function(){
        let params = fn.rateData;
        params.txnMode = form.val("form-txn-info")['txnMode'];
        params.paymentDetails = form.val("form-txn-info")['paymentDetails'];
        request.postForm('/rate/txn/lockRate',params).then(res => {
            layer.msg('交易信息已成功提交',{time:2000});
            //重新进入交易概况数据
            fn.showQueryRate();
            //清空数据
            $("#form-txn-info")[0].reset();
            layui.form.render();

            //重新加载交易列表
            fn.clearQuery();
        }).catch(res=>{
            if(res.code != '1') {
               fn.showQueryRate();
            }
        });
    });
    exports('rateSettlement', fn)
})